package com.c1202m.dao;

import codeblue.project.MD5Encode;
import com.c1202m.gui.CustomMessageDialog;
import org.hibernate.Session;

public class DoiMatKhauDAO {

    public boolean userChangPw(String oldPw, String newPw, String confirmPw) {
        if (!MD5Encode.encode(oldPw).equals(DangNhapDAO.quanTri.getMatKhau())) {
            new CustomMessageDialog(null, true, "Oops...!", "<html>The old password you've typed<br>is wrong</html>", CustomMessageDialog.MESSAGE);
            return false;
        }
        if (oldPw.equals(newPw)) {
            new CustomMessageDialog(null, true, "Oops...!", "<html>The new password must be different<br>from the old one.</html>", CustomMessageDialog.MESSAGE);
            return false;
        }
        if (!newPw.equals(confirmPw)) {
            new CustomMessageDialog(null, true, "Oops...!", "<html>The new and the confirm password<br>must be the same.</html>", CustomMessageDialog.MESSAGE);
            return false;
        }
        Session session = DangNhapDAO.sessionFactory.openSession();
        try {
            session.getTransaction().begin();
            DangNhapDAO.quanTri.setMatKhau(MD5Encode.encode(newPw));
            session.update(DangNhapDAO.quanTri);
            session.getTransaction().commit();
            session.close();
            return true;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        // if update error
        new CustomMessageDialog(null, true, "Oops...!", "An error occured!", CustomMessageDialog.MESSAGE);
        return false;
    }
}
